import { Dialog } from 'antd-mobile'
import axios from 'axios'
import { useEffect, useState } from 'react'

export function useUpdate() {
  const META_KEY = 'version-no'
  const [curVersion, setCurVersion] = useState<Nullable<string>>(null)
  const [timer, setTimer] = useState<Nullable<number>>(null)
  const [show, setShow] = useState(false)

  function showNotify() {
    setShow(true)

    Dialog.confirm({
      title: '更新提示',
      content: '发现新版本，请刷新后使用哦',
      onConfirm: () => {
        setShow(false)
        window.location.reload()
      }
    })
  }

  function getCurVersion() {
    let version = ''
    const metaList = document.querySelectorAll('meta')

    if (metaList.length) {
      metaList.forEach(item => {
        if (item.name === META_KEY) {
          version = item.content
        }
      })
    }

    setCurVersion(version)
  }

  async function getNewVersion() {
    const timestamp = new Date().getTime()
    const response = await axios.get(
      `${window.location.origin}/${import.meta.env.VITE_APP_NAME}`,
      {
        params: { timestamp }
      }
    )

    const el = document.createElement('html')
    el.innerHTML = response.data

    let newVersion = ''

    const metaList = el.querySelectorAll('meta')

    if (metaList.length) {
      metaList.forEach(item => {
        if (item.name === META_KEY) {
          newVersion = item.content
        }
      })
    }

    console.group('版本检测')
    console.log('现版本：', curVersion)
    console.log('新版本：', newVersion)
    console.groupEnd()

    if (newVersion && newVersion !== curVersion && !show) {
      showNotify()
    }
  }

  function getVersion() {
    getCurVersion()
    getNewVersion()
  }

  function startTimer() {
    const newTimer = setInterval(getNewVersion, 30 * 60 * 1000)
    setTimer(newTimer)
  }

  function clearTimer() {
    if (timer) {
      clearInterval(timer)
      setTimer(null)
    }
  }

  function onVisibilityChange() {
    if (!document.hidden) {
      startTimer()
      getVersion()
    } else {
      clearTimer()
    }
  }

  useEffect(() => {
    const url = window.location.origin

    // 非本地环境生效
    if (!/localhost/.test(url) && !/192\./.test(url)) {
      getVersion()
      startTimer()
      document.addEventListener('visibilitychange', onVisibilityChange)
    }

    return () => {
      clearTimer()
      document.removeEventListener('visibilitychange', onVisibilityChange)
    }
  }, [])
}
